import { defineStore } from "pinia"

export const useUserStore = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        refreshToken: localStorage.getItem('refreshToken') || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
        isAuthenticated: false
    }),
    
    getters: {
        isLogin: (state) => !!state.token && !!state.userInfo,
        username: (state) => state.userInfo?.username || '',
        email: (state) => state.userInfo?.email || '',
        userId: (state) => state.userInfo?.userId || null
    },
    
    actions: {
        // 登录成功后设置用户信息和token
        setUserData(loginResponse) {
            this.token = loginResponse.token
            this.refreshToken = loginResponse.refreshToken || ''
            this.userInfo = {
                username: loginResponse.username,
                email: loginResponse.email,
                userId: loginResponse.userId
            }
            this.isAuthenticated = true
            
            // 持久化存储
            localStorage.setItem('token', this.token)
            if (this.refreshToken) localStorage.setItem('refreshToken', this.refreshToken)
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        },
        
        // 更新access/refresh令牌
        updateTokens(tokens) {
            if (tokens?.token) {
                this.token = tokens.token
                localStorage.setItem('token', this.token)
            }
            if (tokens?.refreshToken) {
                this.refreshToken = tokens.refreshToken
                localStorage.setItem('refreshToken', this.refreshToken)
            }
            this.isAuthenticated = !!this.token && !!this.userInfo
        },
        
        // 登出清除所有用户数据
        logout() {
            this.token = ''
            this.refreshToken = ''
            this.userInfo = null
            this.isAuthenticated = false
            
            // 清除本地存储
            localStorage.removeItem('token')
            localStorage.removeItem('refreshToken')
            localStorage.removeItem('userInfo')
            localStorage.removeItem('lastRefreshDate')
        },
        
        // 初始化用户状态（从本地存储恢复）
        initUserState() {
            const token = localStorage.getItem('token')
            const refreshToken = localStorage.getItem('refreshToken')
            const userInfo = localStorage.getItem('userInfo')
            
            if (token && userInfo) {
                this.token = token
                this.refreshToken = refreshToken || ''
                this.userInfo = JSON.parse(userInfo)
                this.isAuthenticated = true
            }
        },
        
        // 检查token是否过期（可选实现）
        checkTokenExpiration() {
            // TODO: 如果后端提供token过期检查接口，可以在这里实现
            return this.isLogin
        },
        
        // 更新用户信息
        updateUserInfo(newUserInfo) {
            if (this.userInfo) {
                this.userInfo = { ...this.userInfo, ...newUserInfo }
                localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
            }
        }
    },
})
